package cn.yangliu.webflux.web;

import java.time.LocalDateTime;

import cn.yangliu.webflux.entity.User;
import cn.yangliu.webflux.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RequestMapping("/user")
@RestController
@Slf4j
@Api(value = "用户接口", tags = "用户接口")
public class UserWebfluxController {

    /**
     * userService
     */
    private UserService userService;

    @PostMapping
    @ApiOperation(value = "保存", tags = "用户接口", response = User.class)
    public Mono<User> save(@RequestBody User data) {
        return Mono.fromSupplier(() -> userService.save(data));
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查询", tags = "用户接口", response = User.class)
    public Mono<User> get(@PathVariable("id") Long id) {
        return Mono.fromSupplier(() -> {
            User user = userService.findById(id).orElse(null);
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            return user;
        });
    }

    @GetMapping
    @ApiOperation(value = "列表查询", tags = "用户接口")
    public Mono<Page<User>> findAll(int page, int size) {
        PageRequest pageRequest = PageRequest.of(page, size);
        return Mono.fromSupplier(() -> userService.findAll(pageRequest));
    }

    @GetMapping("/test")
    @ApiOperation(value = "测试异常", tags = "用户接口")
    public Mono<User> test() {
       throw new UnsupportedOperationException("测试异常");
    }

    @PutMapping
    @ApiOperation(value = "修改", tags = "用户接口", response = User.class)
    public Mono<User> update(@RequestBody User data) {
        log.info("-=-----------------------" + data.getId());
        return Mono.fromSupplier(() -> userService.save(data));
    }


    /**
     * @param userService userService
     */
    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

}
